/**
 * 异步化api
 * @param {*} api 
 */
const pify = api => params =>
	new Promise((resolve, reject) => {
		if (!api) {
			wx.showModal({
				title: "提示",
				content:
					"当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试",
				complete: () => reject(),
				confirmColor: "#006eff",
				showCancel: false
			});
		} else {
			api.call(wx, { ...params, success: resolve, fail: reject });
		}
    });
/**
 * 函数节流
 * @param  {Number} delay  节流时间
 *  @param  {Boolean} noTrailing true 在节流过后不会执行
 *  @param  {Function} callback    回调函数
 *  @param  {Boolean} debounceMode true 关闭
 * @description doc https://github.com/niksy/throttle-debounce
 */
export const throttle=  function(delay, noTrailing, callback, debounceMode) {
    var timeoutID;

    var lastExec = 0;

    if (typeof noTrailing !== 'boolean') {
        debounceMode = callback;
        callback = noTrailing;
        noTrailing = undefined;
    }

    function wrapper() {
        var self = this;
        var elapsed = Number(new Date()) - lastExec;
        var args = arguments;

        function exec() {
            lastExec = Number(new Date());
            callback.apply(self, args);
        }

        function clear() {
            timeoutID = undefined;
        }

        if (debounceMode && !timeoutID) {
            exec();
        }

        if (timeoutID) {
            clearTimeout(timeoutID);
        }

        if (debounceMode === undefined && elapsed > delay) {
            exec();
        } else if (noTrailing !== true) {
            timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
        }
    }

    wrapper.cancel = function() {
        clearTimeout(timeoutID);
    };

    return wrapper;
}
export const pifyGetImageInfo = pify(wx.getImageInfo);
export const pifyCanvasToTempFilePath = pify(wx.canvasToTempFilePath);
export const pifyChooseImage = pify(wx.chooseImage);
export const pifyShowModal = pify(wx.showModal);

export const touchThrottle = (fn = () => {}) => throttle(50, true, fn);

	/**
	 * 获取错误信息
	 * @param {Object|String} err
	 * @param defaultMsg
	 * @return {*}
	 */
export const getErrorMsg= (err, defaultMsg = "") => {
		if (!err) {
			return "";
		}
		let errorMsg = "";
		if (typeof err === "string") return err;
		if (
			err &&
			typeof err.errMsg === "string" &&
			/cancel/.test(err.errMsg)
		) {
			return "";
		}
		if (typeof err === "object" && "code" in err) {
			if (err.msg) {
				errorMsg = `${err.msg}`;
			} else {
				errorMsg = "网络繁忙";
			}
			if (!codeReg.test(errorMsg)) {
				errorMsg += `(${err.code})`;
			}
		} else {
			errorMsg = defaultMsg || "连接服务器失败，请稍后再试";
		}
		return errorMsg;
	}
	/**
	 * @param {*} content 消息内容
	 * @description
	 * 弹出一个modal展示错误消息
	 */
export const errorDialog=(content = "")=>{
		content = getErrorMsg(content);
		if (!String(content)) {
			return;
		}
		return pifyShowModal({
			title: "错误",
			content: content
		});
	};
